import { APICartList, APICartUpdate, APICartDelete } from './fetch.js';
import { getCookie } from './tools.js';


// $('#head').load('../../layout/head.html');
// $('#foot').load('../../layout/foot.html');

layui.use(['layer'], function () {
  var layer = layui.layer;


  var username = getCookie('login_user');

  APICartList({
    username
  }).then(({ data }) => {
    var html = '';
    $.each(data, (index, { gname, img, price, count, id }) => {
      html += `
      <div id="shop_mid" data-id="${id}">
            <div id="div_a"><input id="check-one" type="checkbox"></div>
            <div id="div_b"><img src="${img}" alt=""></div>
            <div id="div_c"><p>${gname}<br><span>规格：定制诚意金（具体价格以设计方案<br>为准，详情咨询客服）</span></p></div>
            <div id="div_d">￥<span>${price}</span></div>
            <div id="div_e">
                <button id="btn_down">${count > 1 ? '-' : ''}</button>
                <input type="text" id="inp_jiesuan" value="${count}">
                <button id="btn_top">+</button>
            </div>
            <div id="div_f">￥<span id="span_P">${(price * count).toFixed(2)}</span></div>
            <div id="div_g"><a id="delete" href="#">删除</a></div>
      </div>
    `
    })

    $('#shop_box').html(html);

  })

  var timer = null;

  $(document).on('click', '#btn_top', function () {


    updateCount(this, 1);

    $(this).parents('#shop_mid').find('#btn_down').text('-');
    var a = $(this).parents('#shop_mid').find('#span_P').val()*1;
    var b = $(this).parents('#shop_mid').find('#div_d span').val()*1;
    $(this).parents('#shop_mid').find('#span_P').val(a*b);
    setTimeout(() => {
      location.reload()
    }, 500)
    
  })

  $(document).on('click', '#btn_down', function () {
    if (!$(this).text()) return;

    updateCount(this, -1);
    setTimeout(() => {
      location.reload()
    }, 500)
  })


  function updateCount(self, tag) {

    var parent = $(self).parents('#shop_mid');

    var id = parent.attr('data-id');
    var count = parent.find('#inp_jiesuan').val() * 1;

    count += tag;

    if (count <= 1) {
    parent.find('#btn_down').text('');
    }

    parent.find('#inp_jiesuan').val(count);
    var parent = $(self).parents('div_e');
    var price = parent.find('#div_d').text();

    parent.find('#div_f').text((count * price).toFixed(2))

    clearTimeout(timer);
    timer = setTimeout(() => {
      APICartUpdate({
        id,
        count
      }).then(({ code }) => {
        if (code) {

        }
      })
    }, 500)
    getTotal()
  }

  // 全选上
  $('#check-all').change(function () {
    // console.log(666)
    $('#div_a #check-one').prop('checked', $(this).prop('checked'))
    getTotal()
  })
  //全选下
  $('#check-all-A').change(function () {
    // console.log(666)
    $('#div_a #check-one').prop('checked', $(this).prop('checked'))
    getTotal()
  })
  
  // 单选
  $(document).on('click', '#check-one', function () {
    // console.log(666)
    // console.log($('.check-one').length)
    checkAll();
  })

  function checkAll() {
    if ($('#div_a #check-one').length === $('#check-one:checked').length) {
      $('#check-all').prop('checked', true)
    } else {
      $('#check-all').prop('checked', false)
    }
    getTotal()
  }

  // 删除
  $(document).on('click', '#delete', function () {
    APICartDelete({
      ids: JSON.stringify([$(this).parents('#shop_mid').attr('data-id')])
    }).then(({ code, msg }) => {
      if (code) {
        $(this).parents('#shop_mid').remove();
        checkAll();
        layer.msg('删除成功')
      } else {
        layer.msg(msg)
      }
    })
  })

  $('#s_2').click(function () {

    var ids = [];

    $.each($('#check-one:checked'), function (index, item) {
      ids.push($(item).parents('#shop_mid').attr('data-id'))
    })

    APICartDelete({
      ids: JSON.stringify(ids)
    }).then(({ code, msg }) => {
      if (code) {
        $('#check-one:checked').parents('#shop_mid').remove();
        checkAll();
        layer.msg('删除成功');
      } else {
        layer.msg(msg)
      }
    })
  })



})

function getTotal() {
  var count = 0;
  var total = 0;
  $.each($('#div_a #check-one:checked'), function (_, item) {
    count += $(this).parents('#shop_mid').find('#inp_jiesuan').val() * 1
    total +=  $(this).parents('#shop_mid').find('#span_P').text() *1
  });

  $('#s_4 #selectedTotal').text(count);



  $('#s_6 #priceTotal').text(total);
}


